<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="$t('添加')" :v-if="dialogVisible" :visible.sync="dialogVisible" width="850px" @close='close' top="10vh">
    <div class="dialogContentBoxMaxHeight90">
      <el-form ref="form" :inline="true" :model="record" label-width="130px" :rules="rules" label-position="left" style="margin:0 20px;">
        <el-form-item :label="$t('IP类型')" class="autoDetectForm" prop="iptype">
          <el-radio style="margin-left:20px;" v-model="record.iptype" :label="0" class="IPv4">IPv4</el-radio>
          <el-radio v-model="record.iptype" :label="1" class="IPv6">IPv6</el-radio>
        </el-form-item>
        <el-form-item :label="$t('网口')"  class="autoDetectForm" prop="interface">
          <template slot="label">{{$t('网口')}}
            <el-tooltip class="item" effect="light" :content="$t('仅支持路由口同网段地址探测')" placement="top">
              <i class="el-icon-warning-outline" style="color:#666;font-size:14px;"></i>
            </el-tooltip>
          </template>
          <el-select v-model="record.interface" ref="recordInterface" size='small' filterable>
            <el-option v-for="item in interfaceList" :disabled="item.enPortMode === 3" :key="item.strPhysicsName" :label="item.strPhysicsName" :value="item.strPhysicsName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="!record.iptype" class="autoDetectForm" :label="$t('IPv4起始地址')" prop="begin" key="begin">
          <el-input v-emoji v-model="record.begin" style="width:215px;" size='small' ref="recordBegin"></el-input>
        </el-form-item>
        <el-form-item v-if="!record.iptype" class="autoDetectForm"  :label="$t('IPv4结束地址')" prop="end" key="end">
          <el-input v-emoji v-model="record.end" style="width:215px;" size='small' ref="recordEnd"></el-input>
        </el-form-item>
        <el-form-item v-if="record.iptype" class="autoDetectForm" :label="$t('IPv6地址范围')" prop="range" key="range">
          <el-input v-emoji v-model="record.range" style="width:215px;" size='small' ref="recordRange"></el-input>
        </el-form-item>
        <div class="strategyFatherBox">
          <el-button type="success" size='small' @click="listData" class="listData">{{$t('开始探测')}}</el-button>
        </div>
        <el-table ref="multipleTable" size='mini' max-height="400px" :data="autoDetectList" tooltip-effect="dark" @selection-change="autoDetectChange">
          <el-table-column type="selection" align='center' width="55"></el-table-column>
          <el-table-column prop="ip" align='center' label="IP" min-width="200">
            <template slot-scope="scope">
              <tooltip :copyText="scope.row.ip" class="wid190">
              </tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="mac" align='center' label="MAC" min-width="200"></el-table-column>
        </el-table>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="strategy">{{$t('生成策略')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>

import { addBindByAuto, autoDetect } from '@/api/safe/bind'
import { getPhysicalApiArray } from '@/api/network/api/physical'
import { inputClass, selectClass } from '@/utils/input-class.js'
export default {
  name: 'AutoDetectDialog',
  data () {
    var validateBegin = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入IPv4起始地址')))
      } else {
        callback()
      }
    }
    var validateEnd = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入IPv4结束地址')))
      } else {
        callback()
      }
    }
    var validateRange = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入IPv6地址范围')))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      record: {
        iptype: 0,
        interface: '',
        begin: '',
        end: '',
        range: ''
      },
      recordCopy: {
        iptype: 0,
        interface: '',
        begin: '',
        end: '',
        range: ''
      },
      ipmac: '',
      autoDetectList: [],
      interfaceList: [],
      rules: {
        begin: [{ required: false, validator: validateBegin, trigger: 'blur' }],
        end: [{ required: false, validator: validateEnd, trigger: 'blur' }],
        range: [{ required: false, validator: validateRange, trigger: 'blur' }]
      }
    }
  },
  watch: {
    'record.iptype': {
      handler (val) {
        this.autoDetectList = []
        if (val) {
          this.$nextTick(() => {
            const data = ['recordRange']
            inputClass(this.$refs, data)
          })
        }
      }
    }
  },
  methods: {
    init (data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        const data = ['recordBegin', 'recordEnd']
        const selectData = ['recordInterface']
        inputClass(this.$refs, data)
        selectClass(this.$refs, selectData)
      })
      getPhysicalApiArray().then(res => {
        this.interfaceList = res.info
        for (let item of this.interfaceList) {
          if (item.enPortMode !== 3) {
            this.record.interface = item.strPhysicsName
            break
          }
        }
      })
    },
    submit () {
      if (this.ipmac) {
        addBindByAuto({ iptype: this.record.iptype, ipmac: this.ipmac }).then(res => {
          if (res.status === 0) {
            this.$message({
              message: this.$t('添加成功'),
              type: 'success'
            })
            this.close()
            this.$parent.listData()
          }
        }).catch(e => {
          if (e.status === -20) {
            this.$parent.listData()
          }
        })
      } else {
        this.$message({
          message: this.$t('请至少选择一条数据进行添加'),
          type: 'error'
        })
      }
    },
    listData () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          autoDetect(this.record).then(res => {
            if (res.status === 0) {
              this.autoDetectList = res.info.sort((a, b) => {
                const ip1 = a.ip.split('.').map(e => e.padStart(3, '0')).join('')
                const ip2 = b.ip.split('.').map(e => e.padStart(3, '0')).join('')
                return ip1 - ip2
              })
            }
          })
        }
      })
    },
    autoDetectChange (data) {
      let ipmac = ''
      for (let item of data) {
        ipmac += item.ip + '/' + item.mac + ','
      }
      this.ipmac = ipmac
    },
    close () {
      this.dialogVisible = false
      this.ipmac = ''
      this.autoDetectList = []
      this.interfaceList = []
      this.record = Object.assign({}, this.recordCopy)
      this.$refs.form.resetFields()
    }
  }
}
</script>
<style>
.autoDetectForm {
  width: 350px;
}
</style>
